﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Tools;
using System.Windows.Forms;


using System.Management;//References也要引用，在.NET里
using System.IO;
using System.Diagnostics;

namespace GitFileList
{
    public  class Program
    {
        static void Main(string[] args)
        {
            Run run= new Run();
            if (run.LoadConfig(@"\\10.1.131.192\SharedDocs"))
            {
                File.WriteAllText("filelist.data",run._FileList.ToString("json"));
                run._FileList.Changed = false;

                run.CheckCopyXiaoTiResult();
            }
        }
        
    }
    public class Run
    {
        public Run()
        {
        }
        public Boolean LoadConfig(string replacepath = "")
        {
            Boolean OK = false;
             bool status = false;
            string filepath = replacepath;


            //连接共享文件夹
            //status = connectState(@"\\dechang.kin.net", @"kin\wanghaidong", "123456");
            //直接用IP也可以
            status = connectState(filepath);
            ////本机
            //status = connectState(@"\\puter.kin.net", @"kin\wanghaidong", "123456");
            if (status)
            {
                //共享文件夹的目录
                DirectoryInfo theFolder = new DirectoryInfo(filepath);

                GetFileList_ListInfo(replacepath, path);

                path = (path+"_").Replace("Screen_", "ExamResult");
                GetFileList_ExamResultInfo(replacepath, path);
                if (_FileList.Changed)
                    return true;
                //相对共享文件夹的路径，这个路径一般都是映射
                //filepath = @"E:\JHScanPaper1\out\FX";
                ////本机
                //MessageBox.Show(  "文件夹："+theFolder.FullName +" 有文件"  + theFolder.GetDirectories().Count());
                ////获取保存文件的路径
                //string filename = filepath;// theFolder.ToString() + fielpath;
                ////执行方法，把本地D盘的1文件复制到服务器上，并命名2
                ////Transport(@"D:\1.txt", filename, "2.txt");
                ////打开路径（文件夹）
                //System.Diagnostics.Process.Start(theFolder.FullName);
            }
            else
            {
                MessageBox.Show("未能连接！");
            }

           
            return false;;
        }
        private void GetFileList_ListInfo(string replacepath, string path)
        {
            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                ScanDatas _ScanDatas = new ScanDatas(path);
                if (_ScanDatas.Scandatas.Count > 0)
                {
                    _FileList = new FileList();
                    foreach (ScanData sd in _ScanDatas.Scandatas)
                    {
                        CImgList imglist = new CImgList();
                        foreach (string s in sd.ImgList)
                        {
                            string str = s.Substring(sd.Imgpath.Length + 1);
                            imglist.ImgList.Add(str);
                        }
                        imglist.Path = sd.Imgpath.Replace(replacepath, "");
                        _FileList.List.Add(imglist);
                    }
                        _FileList.Changed = true;
                }
            }
        }
        private void GetFileList_ExamResultInfo(string replacepath, string path)
        {
            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                path = path.Substring(0, path.Length - di.Name.Length-1);
                ScanData sd = new ScanData(di.Name, path);

                List<string> filelist = sd.GetFileList(".zip");
                if (filelist.Count > 0)
                {
                    if (_FileList == null)
                        _FileList = new FileList();
                    _FileList.ExamList.Clear();
                    foreach (string s in filelist)
                    {
                        string str = s.Replace(replacepath, "");
                        _FileList.ExamList.Add(new ExamResult(str));
                    }
                    _FileList.Changed = true;
                }               
            }
        }
        public void CheckCopyXiaoTiResult()
        {
            string imgpath = @"F:\out\FX";
            string path = "";// @"E:\Git\GitHome\Source\gitee\";
            foreach (ExamResult exam in _FileList.ExamList)
            {
                string imgfilename = imgpath + exam.PathName + "_小题成绩单.jpg";
                string dstimgfilename = path + exam.Path + ".jpg";
                dstimgfilename = dstimgfilename.Replace("ScreenData\\", "");
                if (!File.Exists(dstimgfilename))
                {
                    if (File.Exists(imgfilename))
                    {
                        File.Copy(imgfilename, dstimgfilename);
                    }
                    else
                    {
                        MessageBox.Show(exam.PathName + "的小题成绩单，无法查询到");
                    }
                }
            }
            //throw new NotImplementedException();
        }
        public FileList _FileList;

    }
    public class ScanDatas
    {
        private List<ScanData> _scandatas;
        private string path;
        public ScanDatas(string path)
        {
            this.path = path;
            _scandatas = new List<ScanData>();
            foreach (string dirname in Tools.FileTools.SubDirNameListFromDir(path))
            {
                ScanData sd = new ScanData(dirname, path);
                if (sd.ImgList.Count > 0)
                    Scandatas.Add(sd);
            }
        }
        public List<ScanData> Scandatas { get { return _scandatas; } }
    }
    public class ScanData
    {
        private string _dirname;
        private string _path;
        private string _examname;
        public ScanData(string dirname, string path)
        {
            this._dirname = dirname;
            this._path = path;
            _examname = dirname;
            if (dirname.Contains("."))
            {
                _examname = dirname.Substring(0, dirname.LastIndexOf("."));
            }
        }
        public override string ToString()
        {
            if (File.Exists(Fullpath + "\\已生成阅卷数据.txt"))
                return _examname + " 已生成阅卷数据";
            return _examname;
        }
        public string Fullpath { get { return _path + "\\" + _dirname; } }
        public string Imgpath { get { return _path + "\\" + _dirname; } }
        public string DataFullName { get { return Fullpath + "\\data.txt"; } }
        public string ExamName { get { return _examname; } }

        public List<string> ImgList { get { return Tools.FileTools.NameListFromDir(Imgpath, ".jpg"); } }
        public List<string> GetFileList(string ext)
        {
            return Tools.FileTools.NameListFromDir(Fullpath,ext); 
        }
    }    

    
        public static bool connectState(string path)
        {
            return connectState(path, "", "");
        }
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }
        /// <summary>
        /// 向远程文件夹保存本地内容，或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="src">要保存的文件的路径，如果保存文件到共享文件夹，这个路径就是本地文件路径如：@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径，不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        public static void Transport(string src, string dst, string fileName)
        {
            FileStream inFileStream = new FileStream(src, FileMode.Open);
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
            byte[] buf = new byte[inFileStream.Length];
            int byteCount;
            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {
                outFileStream.Write(buf, 0, byteCount)
            }
            inFileStream.Flush();
            inFileStream.Close();
            outFileStream.Flush();
            outFileStream.Close();
        }
}
